package com.GLM.Viewer.Message;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.GLM.Constants.Constant;
import com.GLM.Entity.MsgEntity;
import com.GLM.Entity.ReviewEntity;
import com.GLM.Tools.DB.DAO.UserInfoDAO;
import com.GLM.Tools.Utils.Image.AsynImageLoader;
import com.GLM.Tools.Utils.JSON.JSONResponse;
import com.GLM.Tools.Utils.JSON.JSONResponse.Status;
import com.GLM.Tools.Utils.JSON.JSONUtil;
import com.GLM.Viewer.R;
import com.GLM.Viewer.Users.UserInfoDetailActivity;
import com.google.gson.Gson;

public class MessageDetailActivity extends Activity {
	private final static int MESSAGE_COMMENTS_LOADING = 111;
	private final static int MESSAGE_COMMENTS_LONDED = 222;
	
	View mInputFieldMoreLines;
	EditText mInputFieldMoreLinesEditText;

	Animation mAnimIn;
	Animation mAnimOut;
	InputMethodManager imm;
	
	private int mUserId;
	private MsgEntity msgEntity;
	private List<ReviewEntity> msgComments = new ArrayList<ReviewEntity>();
	AsynImageLoader asynImageLoader = new AsynImageLoader();
	private ProgressBar mProgressBar;
	private final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Thread thread;
			switch (msg.what) {
			case MESSAGE_COMMENTS_LOADING:
				mProgressBar.setVisibility(View.VISIBLE);
				thread = new Thread(new Runnable() {
					public void run() {
						loadMessageComments();
						mHandler.sendEmptyMessage(MESSAGE_COMMENTS_LONDED);
					}
				});
				thread.start();
				break;

			case MESSAGE_COMMENTS_LONDED:
				mProgressBar.setVisibility(View.GONE);
				initCommentsView();
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_message_details);
		imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

		initMsgData();
		initAvatar();
		initNicknameAndCreateDate();
		initMsgContents();
		initPicView();
		
		initInputFields();
		initAnimation();
		initRegisterInputFieldButton();
		mProgressBar = (ProgressBar) findViewById(R.id.message_progressbar);
		mHandler.sendEmptyMessage(MESSAGE_COMMENTS_LOADING);
	}

	private void initMsgData() {
		Intent intent = getIntent();
		mUserId = intent.getIntExtra(Constant.MESSAGE_CURRENT_USERID, -1);
		msgEntity = (MsgEntity) intent.getSerializableExtra(Constant.MESSAGE_ENTITY);
	}

	private void initInputFields() {
		mInputFieldMoreLines = findViewById(R.id.inputfield_moreline);
		mInputFieldMoreLines.setVisibility(View.GONE);
		mInputFieldMoreLinesEditText = (EditText) findViewById(R.id.inputfieldmoreline_edittext);
	}

	private void initAnimation() {
		mAnimIn = AnimationUtils.loadAnimation(this, R.anim.anim_register_in);
		mAnimOut = AnimationUtils.loadAnimation(this, R.anim.anim_register_out);
	}

	private void initRegisterInputFieldButton() {
		// more liness
		Button inputMoreLineCancelButton = (Button) findViewById(R.id.inputfieldmoreline_cancelbutton);
		inputMoreLineCancelButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				hideMoreLinesInputField();
			}
		});

		Button inputMoreLineOkButton = (Button) findViewById(R.id.inputfieldmoreline_okbutton);
		inputMoreLineOkButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				String content = mInputFieldMoreLinesEditText.getText().toString().trim();
				if(!content.equals("")){
					hideMoreLinesInputField();
					int status = initCommment(content);
					if(status == 2){
						Toast.makeText(MessageDetailActivity.this, getString(R.string.message_comment_success), Toast.LENGTH_LONG).show();
						msgComments.clear();
						mHandler.sendEmptyMessage(MESSAGE_COMMENTS_LOADING);
						
					}else{
						Toast.makeText(MessageDetailActivity.this, getString(R.string.message_comment_fail), Toast.LENGTH_LONG).show();	
					}
				}
			}
		});
	}

	private void hideMoreLinesInputField() {
		mInputFieldMoreLinesEditText.setText("");
		mInputFieldMoreLinesEditText.clearFocus();
		mInputFieldMoreLines.startAnimation(mAnimOut);
		mInputFieldMoreLines.setVisibility(View.GONE);
		imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
	}

	private void showMoreLinesInputField() {
		mInputFieldMoreLines.startAnimation(mAnimIn);
		mInputFieldMoreLines.setVisibility(View.VISIBLE);
		mInputFieldMoreLinesEditText.requestFocus();
		imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
	}
	
	private void initAvatar() {
		ImageView avatarView = (ImageView) findViewById(R.id.message_detail_avatar);
		String userAvatarId = msgEntity.getMsg_user_avatar();
		if (null != userAvatarId) {
			asynImageLoader.showImageAsyn(avatarView, Constant.URL_USER_SMALL+userAvatarId, R.drawable.glm_white);
		} else {
			avatarView.setBackgroundResource(R.drawable.glm_avarat_testpic);
		}
	}

	private void initNicknameAndCreateDate() {
		TextView nicknameView = (TextView) findViewById(R.id.message_detail_nickname);
		nicknameView.setText(msgEntity.getMsg_user_nickname());
		TextView createdateView = (TextView) findViewById(R.id.message_detail_creatdate);
		createdateView.setText(msgEntity.getMsg_date());
	}

	private void initPicView() {
		ImageView picView = (ImageView) findViewById(R.id.message_detail_pic);
		String picName = msgEntity.getMsg_picture();
		if (null != picName && !picName.equals("")) {
			asynImageLoader.showImageAsyn(picView, Constant.URL_MESSAGEPIC_MIDDLE + picName, R.drawable.glm_avarat_testpic);
		}
		else{
			picView.setVisibility(View.GONE);
		}
	}

	private void initMsgContents() {
		TextView contentView = (TextView) findViewById(R.id.message_detail_content);
		contentView.setText(msgEntity.getMsg_content());
	}

	private void initCommentsView() {
		if (msgComments.size() > 0) {
			LinearLayout commentsView = (LinearLayout) findViewById(R.id.message_comments);
			for (int i = 0; i < msgComments.size(); i++) {
				addComment(commentsView, msgComments.get(i), i % 2 == 0);
			}
			commentsView.invalidate();
			ScrollView contents = (ScrollView) findViewById(R.id.message_contents);
			
			contents.invalidate();
		}
	}
	
	
	private void addComment(LinearLayout commentsView, ReviewEntity reviewEntity, boolean isLeft) {
		FrameLayout layout = new FrameLayout(this);
		layout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		TextView commentBodyText = new TextView(this);
		FrameLayout.LayoutParams titleLp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER);
		titleLp.setMargins(0, 10, 0, 10);
		commentBodyText.setLayoutParams(titleLp);
		commentBodyText.setGravity(Gravity.CENTER_VERTICAL);
		if (isLeft) {
			
			commentBodyText.setBackgroundResource(R.drawable.glm_reviewleft);
		} else {
			commentBodyText.setBackgroundResource(R.drawable.glm_reviewright);
		}
		commentBodyText.setText(reviewEntity.getRev_content());
		Log.d("reviewEntityTextView", reviewEntity.getRev_content());
		commentBodyText.setTextSize(18);
		
		layout.addView(commentBodyText);
		commentsView.addView(layout);
		commentsView.invalidate();
	}

	private void loadMessageComments() {
		JSONObject request = new JSONObject();
		try {
			request.put(Constant.PARAM_MSGID, msgEntity.getMsg_id());
			JSONResponse jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_GETMESSAGECOMMENTS, request);
			if (jsonResponse.getStatus() != Status.ERR) {
				JSONObject data = jsonResponse.getData();
				int status = -1;
				status = data.getInt(Constant.RESP_STATUS);
				if (status == Constant.RESP_STATUS_SUCCESS) {
					JSONArray jsonArray = data.getJSONArray(Constant.RESP_MESSAGE_ALLREVIEWS);
					initCommentsFromJSONObject(jsonArray);
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	private void initCommentsFromJSONObject(JSONArray jsonArray) throws JSONException {
		Gson gson = new Gson();
		for (int i = 0; i < jsonArray.length(); i++) {
			ReviewEntity review = gson.fromJson(jsonArray.getJSONObject(i).toString(), ReviewEntity.class);
			msgComments.add(review);
		}
	}

	public void likeButton_onClick(View v) {
		int status = initLike();
		if(status == 2){
			Toast.makeText(MessageDetailActivity.this, getString(R.string.message_like_success), Toast.LENGTH_LONG).show();
		}else {
			Toast.makeText(MessageDetailActivity.this, getString(R.string.message_like_fail), Toast.LENGTH_LONG).show();
		}
	}

	public void commentButton_onClick(View v) {
		showMoreLinesInputField();
	}

	public void userInfo_onClick(View v) {
		Intent intent = new Intent(this, UserInfoDetailActivity.class);
		intent.putExtra(Constant.INTENT_USER_ID, mUserId);
		startActivity(intent);
	}

	public void goBackButton_OnClick(View v) {
		NavUtils.navigateUpFromSameTask(this);
	}
	
	public int initLike(){
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = null;
		int status = -1;
		try {
			int user_id = UserInfoDAO.getUserInfo(MessageDetailActivity.this).getUserId();
			jsonData.put(Constant.PARAM_USERID, user_id);
			jsonData.put("msg_id", msgEntity.getMsg_id());
			jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_LIKEMESSAGE , jsonData);
			if (jsonResponse.getStatus() != Status.ERR) {
				JSONObject data = jsonResponse.getData();
				status = data.getInt(Constant.RESP_STATUS);
				
			}
		} catch (Exception e) {
			// TODO: handle exception

		}
		return status; 
	}
	
	public int initCommment(String comContent){
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = null;
		int status = -1;
		try {
			int user_id = UserInfoDAO.getUserInfo(MessageDetailActivity.this).getUserId();
			jsonData.put(Constant.PARAM_USERID, user_id);
			jsonData.put("msg_id", msgEntity.getMsg_id());
			jsonData.put("rev_content", comContent);
			jsonResponse = JSONUtil.postRequest(Constant. REQ_WAY_MESSAGECOMMENT, jsonData);
			if (jsonResponse.getStatus() != Status.ERR) {
				JSONObject data = jsonResponse.getData();
				status = data.getInt(Constant.RESP_STATUS);
				
			}
		} catch (Exception e) {
			// TODO: handle exception

		}
		return status; 
	}
}
